<template>
  <r-header />
  <div class="quiz-container">
    <!-- 题目导航栏 -->
    <div class="question-nav" v-if="questions.length > 0">
      <h2>刷题练习</h2>
      <div class="nav-buttons">
        <button 
          v-for="(question, index) in questions" 
          :key="index"
          :class="['nav-btn', { 
            'active': currentQuestion === index,
            'answered': answers[index] !== null,
            'current': currentQuestion === index
          }]"
          @click="goToQuestion(index)"
        >
          {{ index + 1 }}
        </button>
      </div>
    </div>

    <!-- 题目内容 -->
    <div class="question-content" v-if="questions.length > 0">
      <div class="question-header">
        <h3>第 {{ currentQuestion + 1 }} 题</h3>
        <div class="progress">
          <span>{{ currentQuestion + 1 }} / {{ questions.length }}</span>
        </div>
      </div>

      <div class="question-body">
        <p class="question-text">{{ questions[currentQuestion].question }}</p>
        
        <div class="options">
          <label 
            v-for="(option, optionIndex) in questions[currentQuestion].options" 
            :key="optionIndex"
            :class="['option-item', { 
              'selected': answers[currentQuestion] === optionIndex 
            }]"
          >
            <input 
              type="radio" 
              :name="`question_${currentQuestion}`"
              :value="optionIndex"
              v-model="answers[currentQuestion]"
              @change="selectAnswer(optionIndex)"
            />
            <span class="option-label">{{ String.fromCharCode(65 + optionIndex) }}.</span>
            <span class="option-text">{{ option }}</span>
          </label>
        </div>
      </div>

      <!-- 导航按钮 -->
      <div class="question-navigation">
        <button 
          class="nav-button prev" 
          @click="previousQuestion"
          :disabled="currentQuestion === 0"
        >
          上一题
        </button>
        
        <button 
          class="nav-button next" 
          @click="nextQuestion"
          :disabled="currentQuestion === questions.length - 1"
        >
          下一题
        </button>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-section" v-if="questions.length > 0">
      <button 
        class="submit-btn" 
        @click="submitQuiz"
        :disabled="!canSubmit"
        :class="{ 'disabled': !canSubmit }"
      >
        {{ canSubmit ? '提交试卷' : `还需完成 ${remainingQuestions} 题` }}
      </button>
    </div>
    
    <!-- 加载状态或空状态 -->
    <div v-if="questions.length === 0" class="loading-section">
      <div class="loading-content">
        <h3>正在加载题目...</h3>
        <p>如果没有题目数据，将显示默认题目</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'QuizTest',
  data() {
    return {
      currentQuestion: 0,
      answers: [],
      questions: []
    }
  },
  computed: {
    // 计算剩余未完成的题目数量
    remainingQuestions() {
      return this.answers.filter(answer => answer === null).length;
    },
    // 是否可以提交（所有题目都已完成）
    canSubmit() {
      return this.answers.every(answer => answer !== null);
    }
  },
  methods: {
    // 选择答案
    selectAnswer(optionIndex) {
      this.answers[this.currentQuestion] = optionIndex;
    },
    
    // 跳转到指定题目
    goToQuestion(index) {
      this.currentQuestion = index;
    },
    
    // 上一题
    previousQuestion() {
      if (this.currentQuestion > 0) {
        this.currentQuestion--;
      }
    },
    
    // 下一题
    nextQuestion() {
      if (this.currentQuestion < this.questions.length - 1) {
        this.currentQuestion++;
      }
    },
    
    // 提交试卷
    async submitQuiz() {
      if (!this.canSubmit) {
        alert('请完成所有题目后再提交！');
        return;
      }
      
      // 计算得分
      let score = 0;
      this.answers.forEach((answer, index) => {
        if (answer === this.questions[index].correct) {
          score++;
        }
      });
      
      // 转换答案格式为后端需要的格式
      const answerData = this.answers.map((answer, index) => {
        // 将数字答案转换为字母（0->A, 1->B, 2->C, 3->D）
        const answerLetter = String.fromCharCode(65 + answer);
        return {
          questionId: index + 1,
          userAnswer: answerLetter
        };
      });
      
      // 显示结果
      const percentage = Math.round((score / this.questions.length) * 100);
      
      // 可以在这里添加更多逻辑，比如保存成绩、跳转页面等
      console.log('提交的答案：', this.answers);
      console.log('转换后的答案数据：', answerData);
      console.log('得分：', score);
      
      // 获取用户ID和试卷ID（需要从localStorage或其他地方获取）
      const userId = this.$store.state.user?.profile?.id;
      const paperId = localStorage.getItem("paperId");
      
      if (!userId || !paperId) {
        alert(`考试完成！\n得分：${score}/${this.questions.length}\n正确率：${percentage}%`);
        return;
      }
      
      // 保存用户答案到localStorage，供结果页面使用
      localStorage.setItem("userAnswers", JSON.stringify(this.answers));
      
      // 先跳转到结果页面，让用户立即看到结果
      this.$router.push('/test-result');
      
      // 在后台异步提交到后端（不等待响应）
      fetch('http://localhost:8088/api/test-paper/submit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          paperId: parseInt(paperId),
          userId: userId,
          answers: answerData
        })
      }).then(response => response.json())
        .then(result => {
          if (result.code === 200) {
            console.log('答案已提交到后端，AI点评正在生成');
          } else {
            console.warn('后端提交失败:', result.msg);
          }
        })
        .catch(error => {
          console.error('提交答案失败:', error);
        });
    },
    
    // 加载题目数据
    loadQuestions() {
      const savedQuestions = localStorage.getItem("generatedQuestions");
      if (savedQuestions) {
        try {
          this.questions = JSON.parse(savedQuestions);
          this.answers = new Array(this.questions.length).fill(null);
          console.log('成功加载题目数据:', this.questions.length, '道题');
        } catch (error) {
          console.error('解析题目数据失败:', error);
          this.loadDefaultQuestions();
        }
      } else {
        this.loadDefaultQuestions();
      }
    },
    
    // 加载默认题目（作为备用）
    loadDefaultQuestions() {
      this.questions = [
        {
          question: "JavaScript中，以下哪个方法可以用于向数组末尾添加元素？",
          options: [
            "push()",
            "pop()",
            "shift()",
            "unshift()"
          ],
          correct: 0
        },
        {
          question: "在Vue.js中，以下哪个指令用于条件渲染？",
          options: [
            "v-for",
            "v-if",
            "v-bind",
            "v-model"
          ],
          correct: 1
        },
        {
          question: "CSS中，以下哪个属性用于设置元素的背景颜色？",
          options: [
            "color",
            "background-color",
            "border-color",
            "text-color"
          ],
          correct: 1
        },
        {
          question: "HTML中，以下哪个标签用于创建表格？",
          options: [
            "<div>",
            "<table>",
            "<form>",
            "<section>"
          ],
          correct: 1
        },
        {
          question: "以下哪个是JavaScript的数据类型？",
          options: [
            "String",
            "Integer",
            "Float",
            "Character"
          ],
          correct: 0
        },
        {
          question: "在CSS中，以下哪个选择器优先级最高？",
          options: [
            "类选择器",
            "ID选择器",
            "标签选择器",
            "属性选择器"
          ],
          correct: 1
        },
        {
          question: "Vue.js中，以下哪个生命周期钩子在组件创建时最先执行？",
          options: [
            "mounted",
            "created",
            "beforeCreate",
            "beforeMount"
          ],
          correct: 2
        },
        {
          question: "以下哪个HTTP状态码表示请求成功？",
          options: [
            "200",
            "404",
            "500",
            "301"
          ],
          correct: 0
        },
        {
          question: "在JavaScript中，以下哪个运算符用于严格相等比较？",
          options: [
            "==",
            "===",
            "!=",
            "!=="
          ],
          correct: 1
        },
        {
          question: "以下哪个是前端框架？",
          options: [
            "React",
            "Express",
            "Django",
            "Spring"
          ],
          correct: 0
        }
      ];
      this.answers = new Array(this.questions.length).fill(null);
    }
  },
  mounted() {
    this.loadQuestions();
  }
}
</script>

<style lang="scss" scoped>
.quiz-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  padding-top: 80px; // 为固定导航栏留出空间
  padding-bottom: 40px;
  color: #ffffff;
}

.question-nav {
  background: rgba(31, 41, 55, 0.9);
  padding: 1.5rem 2rem;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 2rem;

  h2 {
    color: #ffffff;
    margin-bottom: 1rem;
    font-size: 1.5rem;
    text-align: center;
  }

  .nav-buttons {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 0.5rem;
    max-width: 400px;
    margin: 0 auto;

    .nav-btn {
      width: 40px;
      height: 40px;
      border: 2px solid #374151;
      background: #1f2937;
      color: #9ca3af;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      font-weight: 600;

      &:hover {
        border-color: #3b82f6;
        background: #1e40af;
        color: #ffffff;
      }

      &.active {
        border-color: #3b82f6;
        background: #3b82f6;
        color: #ffffff;
      }

      &.answered {
        border-color: #10b981;
        background: #10b981;
        color: #ffffff;
      }

      &.current {
        box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
      }
    }
  }
}

.question-content {
  max-width: 800px;
  margin: 0 auto;
  padding: 0 2rem;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding: 1rem;
  background: rgba(31, 41, 55, 0.8);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);

  h3 {
    color: #ffffff;
    font-size: 1.25rem;
    margin: 0;
  }

  .progress {
    color: #9ca3af;
    font-weight: 600;
  }
}

.question-body {
  background: rgba(31, 41, 55, 0.8);
  border-radius: 12px;
  padding: 2rem;
  border: 1px solid rgba(255, 255, 255, 0.1);
  margin-bottom: 2rem;

  .question-text {
    font-size: 1.1rem;
    line-height: 1.6;
    margin-bottom: 2rem;
    color: #ffffff;
  }

  .options {
    display: flex;
    flex-direction: column;
    gap: 1rem;

    .option-item {
      display: flex;
      align-items: center;
      padding: 1rem;
      background: rgba(55, 65, 81, 0.5);
      border: 2px solid transparent;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(55, 65, 81, 0.8);
        border-color: #3b82f6;
      }

      &.selected {
        background: rgba(59, 130, 246, 0.2);
        border-color: #3b82f6;
      }

      input[type="radio"] {
        margin-right: 1rem;
        transform: scale(1.2);
      }

      .option-label {
        font-weight: 600;
        color: #3b82f6;
        margin-right: 0.5rem;
        min-width: 20px;
      }

      .option-text {
        color: #ffffff;
        flex: 1;
      }
    }
  }
}

.question-navigation {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;

  .nav-button {
    padding: 0.75rem 1.5rem;
    border: 2px solid #374151;
    background: #1f2937;
    color: #ffffff;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s ease;
    font-weight: 600;

    &:hover:not(:disabled) {
      border-color: #3b82f6;
      background: #3b82f6;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }
  }
}

.submit-section {
  text-align: center;
  max-width: 800px;
  margin: 0 auto;
  padding: 0 2rem;

  .submit-btn {
    padding: 1rem 2rem;
    font-size: 1.1rem;
    font-weight: 600;
    border: none;
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    min-width: 200px;

    &:not(.disabled) {
      background: linear-gradient(135deg, #10b981, #059669);
      color: #ffffff;
      box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);

      &:hover {
        background: linear-gradient(135deg, #059669, #047857);
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
      }
    }

    &.disabled {
      background: #374151;
      color: #9ca3af;
      cursor: not-allowed;
    }
  }
}

.loading-section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  text-align: center;

  .loading-content {
    h3 {
      color: #ffffff;
      margin-bottom: 1rem;
      font-size: 1.5rem;
    }

    p {
      color: #9ca3af;
      font-size: 1rem;
    }
  }
}

@media (max-width: 768px) {
  .quiz-container {
    padding: 80px 1rem 40px;
  }

  .question-nav {
    padding: 1rem;

    .nav-buttons {
      grid-template-columns: repeat(5, 1fr);
      gap: 0.25rem;
      max-width: 300px;

      .nav-btn {
        width: 35px;
        height: 35px;
        font-size: 0.9rem;
      }
    }
  }

  .question-content {
    padding: 0 1rem;
  }

  .question-body {
    padding: 1.5rem;

    .options .option-item {
      padding: 0.75rem;
    }
  }

  .question-navigation {
    flex-direction: column;
    gap: 1rem;

    .nav-button {
      width: 100%;
    }
  }
}
</style>
